package com.rcloud.stock.ui.hq;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.rcloud.stock.bean.Stock;
import com.rcloud.stock.net.ServerAddress;
import com.rcloud.stock.net.VolleySingleton;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static android.content.ContentValues.TAG;

public class HqViewModel extends AndroidViewModel {

    public HqViewModel(@NonNull Application application) {
        super(application);
    }
    private final MutableLiveData<List<Stock>> stocks = new MutableLiveData<>();
    public int start = 0;
    public int end = 200;
    public int pageSize = 200;
    public MutableLiveData<List<Stock>> getStocksLive(){
        return stocks;
    }
    public void fetchStocks(String type){
        StringRequest request = new StringRequest(Request.Method.GET,
                ServerAddress.ROOT+"get_stocks?type="+type+"&start="+start+"&end="+end,
                response -> {
                    Gson gson = new Gson();
                    Stock[] temp = gson.fromJson(response,Stock[].class);
                    if (temp!=null){
                        if (end==pageSize){
                            stocks.setValue(Arrays.asList(temp));
                        }else{
                            if (stocks.getValue()!=null){
                                List<Stock> stockList = new ArrayList<>(stocks.getValue());
                                stockList.addAll(Arrays.asList(temp));
                                stocks.setValue(stockList);
                            }
                        }
                        Log.d(TAG,"fetchStocks: "+response);
                    }
                },error -> {
        });
        request.setRetryPolicy(new DefaultRetryPolicy(60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        RequestQueue queue = VolleySingleton.getInstance(getApplication()).getRequestQueue();
        queue.add(request);
    }
}